<template>
  <el-dialog v-model="visible" :width="1100" title="组织机构导入" @close="close">
    <div class="org-picker">
      <div class="left">
        <el-tree ref="tree1" class="draggable-tree" draggable :allow-drop="(_e) => false" :data="gData"
          @node-drag-start="onDragstart" :allow-drag="allowDrag" />
      </div>
      <div class="right" style="" @drop="onTopDrop" @dragover="(e) => e.preventDefault()">
        <el-tree ref="tree2" class="draggable-tree" draggable :data="gData1" :allow-drop="(_e) => true"
          :allow-drag="allowDrag">
          <template #default="{ node, data }">
            <span style="display: flex; justify-content: space-between; align-items: center">
              <span class="node-title">{{ node.label }}</span>
              <Icon icon="ep:delete" class="ml-4" @click="deleteTreeNode(data)" v-if="data.slots" />
            </span>
          </template>
        </el-tree>
      </div>
    </div>
    <el-divider content-position="left">提示：请在左侧选中要导入的节点，然后拖动到右侧</el-divider>
    <template #footer>
      <div class="flex justify-end">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="okHandler" :loading="state.loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, unref, toRaw, onMounted, watch } from 'vue';
import { TreeDataItem } from 'ant-design-vue/es/tree/Tree';
import { DeleteOutlined } from '@ant-design/icons-vue';
import { queryAllSysOrg, batchAddOrgToTree } from '/@/api/organization';
import { replaceFields } from '/@/utils/treeData';
import { Icon } from '/@/components/Icon';

const emit = defineEmits(['success', 'update:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  orgTreeData: {
    type: Array,
    default: () => [],
  },
});

const state = reactive({
  loading: false,
});

const { orgTreeData, visible } = toRefs(props);

const tree1 = ref();
const tree2 = ref();
const gData1 = ref([]) as any;
watch(
  () => toRaw(unref(visible)),
  (nv) => {
    if (nv) {
      gData1.value =
        (formatTreeData(JSON.parse(JSON.stringify(orgTreeData.value)), (e, c) => ({
          label: e.orgName,
          value: e.orgId,
          children: c(e._children),
          isDrag: true,
        })) as TreeDataItem[]) || [];
    }
  },
);

const allowDrag = (draggingNode: Node) => {
  return !draggingNode.data.isDrag;
};

const gData = ref<any[]>();
let dragNode = null;

const onDragstart = (node, _event) => {
  let r = JSON.parse(JSON.stringify(toRaw(unref(node.data))));
  dragNode = addBtnToTransferData(r);
};
// 这段代码给数据添加slots字段用来提供删除功能，同时slots字段
// 也会传递给后台，后台会将含有slots的对象作为新建的数据节点,
// 所以slots字段不要删除
const addBtnToTransferData = (s) => {
  if (!s) return [];
  s.slots = { title: 'custom' };
  s.value = `${s.value}_${Date.now()}`;
  if (s.children) {
    s.children.forEach((e) => {
      e.value = `${e.value}_${Date.now()}`;
      addBtnToTransferData(e);
    });
  }
  return s;
};

const onTopDrop = () => {
  if (!dragNode) return;
  gData1.value.push(dragNode);
  dragNode = null;
};

const deleteTreeNode = (node) => {
  let k = node.value;
  let data = gData1.value;
  function ac(tree, key) {
    if (!tree.length) return;
    tree.forEach((e, i) => {
      if (e.value == key) tree.splice(i, 1);
      if (e.children) ac(e.children, key);
    });
  }
  ac(data, k);
};

const okHandler = async () => {
  state.loading = true;
  let ret = replaceFields(JSON.parse(JSON.stringify(gData1.value)), { label: 'title' });
  try {
    const { respCode } = await batchAddOrgToTree({ orgTreeList: ret });
    state.loading = false;
    if (respCode == 200) {
      emit('success');
      emit('update:visible', false);
    }
  } catch (error) {
    state.loading = false;
  }
};
const close = () => {
  emit('update:visible', false);
  gData1.value = formatTreeData(JSON.parse(JSON.stringify(unref(orgTreeData.value))), (e, c) => ({
    label: e.orgName,
    value: e.orgId,
    children: c(e.children),
  }));
};

onMounted(async () => {
  // const { data } = await queryAllSysOrg();
  // // 根节点不可拖动
  // gData.value = formatTreeData(data, (e, c) => ({
  //   label: e.orgName,
  //   value: e.orgId,
  //   ...e,
  //   children: c(e.children),
  //   isDrag: e.parentId == "-1" ? true : false
  // }));
});

const formatTreeData = <T>(s, cf): T[] | undefined => {
  function trans(s) {
    if (!s || !s.length) return undefined;
    let t: T[] = [];
    s.forEach((e) => {
      t.push({ ...cf(e, trans) });
    });
    return t;
  }
  return trans(s);
};
</script>

<style lang="less">
.org-picker {
  display: flex;
  justify-content: space-between;
  padding: 25px;

  .left,
  .right {
    border: 1px solid #d9d9d9;
    padding: 10px;
    height: 400px;
    overflow-y: auto;
  }

  .left {
    flex: 1;
    margin-right: 20px;
  }

  .right {
    flex: 1;
    // width: 300px
  }

  .node-title {
    display: inline-block;
    max-width: 300px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}
</style>
